package terra.network.handler;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import terra.network.packet.Packet;
import terra.network.packet.PacketHandler;


public class PacketDecoder extends FrameDecoder {
	
	public PacketDecoder(){
	}
	
	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {
	    buf.markReaderIndex();
//	    byte id = buf.readByte();
	    Packet p = PacketHandler.getPacketById(buf.readByte());
	    if (p != null) {
	    	if (!p.isDynamicLength()) {
				 if (buf.readableBytes() >= p.getLength()-1) {
					 return PacketHandler.readPacket(p, buf);
				 }
	    	} else {
	    		if (buf.readableBytes() > 4) {
	    			int length = buf.getInt(buf.readerIndex());
	    			if (buf.readableBytes() >= length+4){
						 return PacketHandler.readPacket(p, buf);
	    			}
	    		}
	    	}
	    }
		buf.resetReaderIndex();
		return null;
	}

}
